//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package roadmap_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type NodeOpIndexDbItem struct {
	OpId      string `bson:"_id"`
	RoadmapId string `bson:"roadmapId"`
	NodeId    string `bson:"nodeId"`
	TimeStamp int64  `bson:"timeStamp"`
}

type _NodeOpIndexDao struct {
	mc *mongo.Collection
}

func newNodeOpIndexDao(db *mongo.Database) (*_NodeOpIndexDao, error) {
	mc := db.Collection(db_ns.DB_NS_ROADMAP + "node_op_index")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"roadmapId", 1}, {"nodeId", 1}, {"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_NodeOpIndexDao{mc: mc}, nil
}

func (db *_NodeOpIndexDao) Insert(ctx context.Context, dbItem *NodeOpIndexDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_NodeOpIndexDao) Count(ctx context.Context, roadmapId, nodeId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"roadmapId": roadmapId, "nodeId": nodeId})
	return uint32(count), err
}

func (db *_NodeOpIndexDao) List(ctx context.Context, roadmapId, nodeId string, offset, limit int64) ([]string, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"roadmapId": roadmapId, "nodeId": nodeId},
		options.Find().SetSkip(offset).SetLimit(limit).SetProjection(bson.M{"_id": 1}).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	tmpList := []*NodeOpIndexDbItem{}
	err = cursor.All(ctx, &tmpList)
	if err != nil {
		return nil, err
	}
	retList := []string{}
	for _, item := range tmpList {
		retList = append(retList, item.OpId)
	}
	return retList, nil
}
